<?php

namespace app\index\service;

use app\common\model\jooj_member\MemberIndexInfo as MemberIndexInfoModel;
use app\common\model\jooj_member\MemberIndex as MemberIndexModel;
use app\common\model\jooj_member\ViewMemberIndex as ViewMemberIndexModel;
use app\common\model\jooj_member\MemberVip as MemberVipModel;
use app\common\common\Constants;
use app\common\model\oms\MemberSign as MemberSignModel;
use app\common\model\jsm\Mps;
use app\common\model\oms\Store;
use app\common\model\jooj_member\VipsAddress;
use app\common\model\oms\Staffs;
use app\common\model\jooj_member\MemberFamilys;
use app\common\model\jooj_member\FamilysTies;
use app\common\model\oms\MemberReserve;
use app\common\common\Helper;
use app\common\arvato\CommonPush;
use app\common\service\arvato\ArvatoMemberService;
use app\common\model\oms\Companies as CompaniesModel;
use app\common\model\jooj_member\Tags;
use app\common\service\MemberGetwayService;

class MemberService {

    /**
     * 更新会员相关字段
     * @param type $company_id
     * @param type $params
     * @param type $memberCodeArr
     * @param type $openId
     * @deprecated since version 2017.11.10 leo.xie 不用了
     */
    protected function updateMemberField($company_id, $params, $memberCodeArr, $openId = '') {
        $memberIndexModel = new MemberIndexModel($company_id);
        $memberIndexModel->startTrans();
        $memberIndexInfoModel = new MemberIndexInfoModel($company_id);
        foreach ($params as $key => $item) {
            //如果key在这个目录下，就更新memberIndex对应数据
            $IndexParams = ['vip_id', 'mobile_status', 'name', 'gender', 'birthday', 'header_img',
                'mp_id', 'cardno', 'card_lev'];
            //修改memberIndex的时候会涉及到这几个字段的同步问题
            $vipParams = ['name', 'gender', 'birthday', 'cardno'];
            //如果key在这个目录下，就更新memberIndexInfo对应的数据
            $IndexInfoParams = ['service_p', 'service_store', 'service_qrscene'];
            if (array_search($key, $IndexParams) !== false) {
                $memberIndexModel->updateValue($key, $item, $memberCodeArr);
            }

            if (array_search($key, $vipParams) !== false) {
                $viewMemberIndexModel = new ViewMemberIndexModel($company_id);
                $memberVipModel = new MemberVipModel($company_id);
                //首先查到vip_id,然后根据vip_id去修改vip表的数据
                $viewMemberIndex = $viewMemberIndexModel->getViewMemberIndexByCondition(['account_code' => $openId]);
                if ($viewMemberIndex && !empty($viewMemberIndex['vip_id'])) {
                    //更新vip表
                    $vipId = $viewMemberIndex['vip_id'];
                    $memberVipModel->updateValue($key, $item, $vipId);
                }
            }

            if (array_search($key, $IndexInfoParams) !== false) {
                $memberIndexInfoModel->updateValue($key, $item, $memberCodeArr);
            }
        }

        $memberIndexModel->commit();
        return true;
    }

    /**
     * acrm更新会员相关字段
     * @param type $company_id
     * @param type $params
     * @param type $memberCodeArr
     * @param type $cardno
     */
    public function updateMemberFieldByCardNo($company_id, $params, $memberCodeArr, $cardno) {

        $memberIndexModel = new MemberIndexModel($company_id);
        $memberIndexInfoModel = new MemberIndexInfoModel($company_id);

        foreach ($params as $key => $item) {
            //如果key在这个目录下，就更新memberIndex对应数据
            $IndexParams = ['vip_id', 'mobile_status', 'name', 'gender', 'birthday', 'header_img', 'come_from',
                'mp_id', 'cardno', 'card_lev', 'account_code', 'mobile'];

            //修改memberIndex的时候会涉及到这几个字段的同步问题
            $vipParams = ['name', 'gender', 'birthday'];

            //如果key在这个目录下，就更新memberIndexInfo对应的数据
            $IndexInfoParams = ['service_p', 'service_store', 'service_qrscene'];

            if (array_search($key, $IndexParams) !== false) {
                $memberIndexModel->updateValue($key, $item, $memberCodeArr);
            }

            if (array_search($key, $vipParams) !== false) {

                $viewMemberIndexModel = new ViewMemberIndexModel($company_id);
                $memberVipModel = new MemberVipModel($company_id);
                //首先查到vip_id,然后根据vip_id去修改vip表的数据
                $viewMemberIndex = $viewMemberIndexModel->getViewMemberIndexByCondition(['cardno' => "$cardno"]);

                if ($viewMemberIndex && !empty($viewMemberIndex['vip_id'])) {
                    //更新vip表
                    $vipId = $viewMemberIndex['vip_id'];
                    $memberVipModel->updateValue($key, $item, $vipId);
                }
            }

            if (array_search($key, $IndexInfoParams) !== false) {
                $memberIndexInfoModel->updateValue($key, $item, $memberCodeArr);
            }
        }

        return true;
    }

    /**
     * 会员资料注册
     * @param array $params
     * @return type
     * 2017.11.10 不用了
     */
    protected function registerMember($params, $companyId) {
        $memberIndexModel = new MemberIndexModel($companyId);
        $memberVipModel = new MemberVipModel($companyId);
        $memberIndexModel->startTrans();
        try {
            $data = $this->registerMemberInfo($params, $companyId);
            if (false === $data['status']) {
                throw new \think\Exception($data['desc']);
            }
            $data['data'] = $this->checkEmptyData($data['data']);
            $data['data'] = $this->convertUnderline($data['data']);
            //$pushToRedis = $this->pushMemberInfoToRedis($data['data']['memberCode'], $companyId);
            if (empty($pushToRedis)) {
                throw new \think\Exception('插入缓存失败');
            }
            $creteCarNo = $this->createCardNo($data['data']['jjUniId'], $params['companyCode']);

            if (0 === $creteCarNo['status']) {
                throw new \think\Exception('推入CRM系统失败' . $creteCarNo['msg']);
            }
            if (empty($creteCarNo['data'])) {
                throw new \think\Exception('新增会员卡号推送失败');
            }

            $updataMemberInfo = $memberIndexModel->updateMemberIndex(['member_code' => $data['data']['memberCode']], $creteCarNo['data']);
            $updataMemberVipInfo = $memberVipModel->updateMemberVip(['member_code' => $data['data']['memberCode']], $creteCarNo['data']);
            if ((false === $updataMemberInfo['status']) || (false === $updataMemberVipInfo['status'])) {
                throw new \think\Exception('新增会员卡号失败');
            }

            $data['data']['cardno'] = $creteCarNo['data']['cardno'];
            $data['data']['cardLev'] = $creteCarNo['data']['card_lev'];
            //签到 开始服务

            $params['comeFrom'] = Constants::$comefromCfg[$params['comeFrom']];
            $signData = [
                'memberCode' => $data['data']['memberCode'],
                'serviceStore' => $data['data']['firstStore'],
                'comeFrom' => $params['comeFrom'],
                'serviceP' => $data['data']['firstP'],
            ];
            $memberSignModel = new \app\common\model\oms\MemberSign($companyId);
            $memberSignModel->memberCheckin($signData);
            $memberIndexModel->commit();
        } catch (\Exception $e) {
            $memberIndexModel->rollback();
            return ['status' => 0, 'desc' => $e->getMessage(), 'data' => (object) []];
        }

        return $data;
    }

    /**
     * 注册会员
     * @param type $params
     * @return type
     */
    private function registerMemberInfo($params, $companyId) {
        switch ($params['mobileStatus']) {
            case 1:
                $res = $this->registerVipMember($params, $companyId); //会员
                break;
            case 2:
                $res = $this->registerIndexMember($params, $companyId); //粉丝、潜客 
                break;
        }
        return $res;
    }

    /**
     * 生成会员卡号规则
     * @author
     * @date 2016-03-25
     * @param int $JjUniId jj_uni_id
     * @param int $companyCode 公司编号
     * @param int $head 卡号头
     * @param int $length 卡号中间自增长数字长度
     * @param int $rand 卡号末尾随机数长度
     */
    protected function createCardNo($JjUniId = '', $companyCode = '', $head = 99, $length = 12, $rand = 2) {
        $MemberGetwayService = new MemberGetwayService();
        return $MemberGetwayService->createCardNo($JjUniId, $companyCode, $head, $length = 12, $rand = 2);
    }

    /**
     * 注册验证是否存在  在手机注册验证的时候就已经验证过了 这里再次验证下 但不返回数据了
     * @param type $params
     * @return type []
     */
    public function checkIndexMember($params, $companyId) {
        $viewMemberModel = new MemberIndexModel($companyId);
        if (empty($params['mobile']) && !isset($params['mobile'])) {
            $condition = [
                'name' => $params['name'],
                'birthday' => $params['birthday'],
                'gender' => $params['gender'],
            ];
        } else {
            return $viewMemberModel->field($field)->where(['mobile' => $params['mobile']])->order('member_code desc')->select();
        }
        return $viewMemberModel->field($field)->where($condition)->order('member_code desc')->select();
    }

    /**
     * 注册潜客与粉丝
     * @param type $params
     * @param type $companyId
     * @param type $status
     * @return type
     * 2017.11.10 leo.xie不用了
     */
    protected function registerIndexMember($params, $companyId) {
        $viewMemberModel = new ViewMemberIndexModel($companyId);
        $memberIndexModel = new MemberIndexModel($companyId);
        $memberIndexInfoModel = new MemberIndexInfoModel($companyId);
        $list = $this->checkIndexMember($params, $companyId);
        if ($list && empty($params['mobile'])) {
            $params['member_code'] = $list[0]['member_code'];
            //更新写入账号服务信息表
            $memberIndexInfoModel->updateIndexInfo($params);
            $data = $viewMemberModel->getIndexAndvipData(['member_code' => $params['member_code']]);
            return ['status' => 0, 'desc' => '已经存在相同的账号信息', 'data' => $data];
        } else if ($list && !empty($params['mobile'])) {
            return ['status' => 0, 'desc' => '此手机号已经被注册过了,请换个手机号试试', 'data' => (object) []];
        }

        $addUser = $memberIndexModel->addUser($params);
        if (empty($addUser)) {
            return ['status' => 0, 'desc' => '创建index表数据失败', 'data' => (object) []];
        }
        $params['member_code'] = $addUser->member_code;
        $params['jjUniId'] = $addUser->jj_uni_id;
        //写入账号服务信息表
        $addMemberIndexInfo = $memberIndexInfoModel->addMemberIndexInfo($params);
        if (false === $addMemberIndexInfo) {
            return ['status' => 0, 'desc' => '创建memberIndex表数据失败', 'data' => (object) []];
        }

        //$data = $viewMemberModel->getIndexAndvipData(['member_code' => $params['member_code']]);
        $message = '粉丝';
        //签到 开始服务
        $signData = [
            'member_code' => $params['member_code'],
            'service_store' => $params['firstStore'],
            'come_from' => 4,
            'service_p' => $params['firstP'],
        ];
        $memberSignModel = new \app\common\model\oms\MemberSign($companyId);

        $CompaniesModel = new CompaniesModel();
        $Companies = $CompaniesModel->getCompanyInfoByCondition('*', ['company_id' => $companyId]);

        $memberSignModel->memberCheckin($signData, $Companies['company_code']);

        return ['status' => true, 'desc' => '恭喜您,注册' . $message . '成功', 'data' => $params];
    }

    /**
     * 注册VIP
     * @param array $params
     * @param boolean $status
     * @return type
     * 2017.11.10不用了
     */
    protected function registerVipMember($params, $companyId) {

        $list = $this->checkIndexMember($params, $companyId);
        if ($list) {
            return ['status' => 0, 'desc' => '此手机号已经被注册过了,请换个手机号试试', 'data' => []];
        }
        $memberVipModel = new MemberVipModel($companyId);
        $memberIndexInfoModel = new MemberIndexInfoModel($companyId);
        $memberIndexModel = new MemberIndexModel($companyId);
        $addUser = $memberIndexModel->addUser($params);
        if (empty($addUser->member_code)) {
            return ['status' => 0, 'desc' => '创建memberIndex表数据失败', 'data' => (object) []];
        }
        $params['member_code'] = $addUser->member_code;
        $params['jjUniId'] = $addUser->jj_uni_id;
        //写入账号服务信息表
        $addMemberIndexInfo = $memberIndexInfoModel->addMemberIndexInfo($params);

        if (false === $addMemberIndexInfo) {
            return ['status' => 0, 'desc' => '创建memberIndexInfo表数据失败', 'data' => (object) []];
        }
        //写入到正式会员表
        $vipId = $memberVipModel->addVip($params);
        if (empty($vipId)) {
            return ['status' => 0, 'desc' => '创建VIP表数据失败', 'data' => (object) []];
        }

        //回写vip_id到memberIndex表

        $updatememberIndex = $memberIndexModel->updateMemberIndex(['member_code' => $memberCode], ['vip_id' => $vipId]);
        if (empty($updatememberIndex)) {
            return ['status' => 0, 'desc' => '创建数据更新VIPID失败', 'data' => (object) []];
        }

        $viewMemberIndexModel = new ViewMemberIndexModel($companyId);

        // $data = $viewMemberIndexModel->getIndexAndvipData(['member_code' => $params['member_code']]);
        $message = '正式会员';
        $signData = [
            'member_code' => $memberCode,
            'vip_id' => $vipId,
            'service_store' => $params['firstStore'],
            'come_from' => 4,
            'service_p' => $params['firstP'],
        ];
        $memberSignModel = new \app\common\model\oms\MemberSign($companyId);

        $CompaniesModel = new CompaniesModel();
        $Companies = $CompaniesModel->getCompanyInfoByCondition('*', ['company_id' => $companyId]);

        $memberSignModel->memberCheckin($signData, $Companies['company_code']);

        return ['status' => true, 'desc' => '恭喜您,注册' . $message . '成功', 'data' => $params];
    }

    function convertUnderline($arr, $status = true, $key = '', $ucfirst = false) {
        if (!is_array($arr)) {
            return false;
        }
        foreach ($arr as $k => $value) {
            $str = ucwords(str_replace('_', ' ', $k));
            $str = str_replace(' ', '', lcfirst($str));
            $str = $ucfirst ? ucfirst($str) : $str;
            if (!$status) {
                if ($key) {
                    $this->newArr[$key][$str] = $value;
                }
            } else {
                $this->newArr[$str] = (string) $value;
            }
            if (is_array($value)) {
                unset($this->newArr[$str]);
                $this->convertUnderline($value, false, $str);
            }
        }
        return $this->newArr;
    }

    protected function checkEmptyData($value) {
        foreach ($value as &$v) {
            if (is_array($v)) {
                foreach ($v as &$i) {
                    if (is_null($i)) {
                        $i = '';
                    }
                }
            }
            if (is_null($v)) {
                $v = '';
            }
        }
        return $value;
    }

    /**
     * 更新会员信息
     * @param array $memberData 会员信息
     * 2017.11.10不用了
     */
    protected function updateMemberInfo($memberData, $companyId) {
        // 提取粉丝ID
        $companyCode = $memberData['companyCode'];
        $memberCode = $memberData['memberCode'];
        $vipId = $memberData['vip_id'];
        $memberIndexModel = new MemberIndexModel($companyId);
        $viewMemberModel = new ViewMemberIndexModel($companyId);
        $memberVipModel = new MemberVipModel($companyId);
        $memberIndexModel->startTrans();
        try {
            // 更新当前粉丝的信息
            unset($memberData['companyCode']);
            unset($memberData['memberCode']);
            !empty($memberData['name']) && $updeData['name'] = $memberData['name'];
            !empty($memberData['gender']) && $updeData['gender'] = $memberData['gender'];
            !empty($memberData['birthday']) && $updeData['birthday'] = $memberData['birthday'];
            !empty($memberData['mobile']) && $updeData['mobile'] = $memberData['mobile'];
            !empty($memberData['mobileStatus']) && $updeData['mobileStatus'] = $memberData['mobileStatus'];
            $updateMemberIndex = $memberIndexModel->updateMemberIndex(['member_code' => $memberCode], $updeData);
            if (false === $updateMemberIndex['status']) {
                throw new \think\Exception($memberIndexModel->getError());
            }
            // 获取粉丝数据
            $memberIndexData = $viewMemberModel->getViewInfoByCondition(['member_code' => $memberCode], 'name,gender,birthday, mobile_status, jj_uni_id');
            $currentMemberData = current($memberIndexData);
            $jjUniId = $currentMemberData['jj_uni_id'];
            //四项资料全并且没有会员卡等级，就更新会员卡等级
            // 宝岛
            if (0 != (int) $currentMemberData['birthday'] && 1 == $currentMemberData['mobile_status'] && false === empty($currentMemberData['name']) && false === empty($currentMemberData['gender']) && (Constants::$cardLev['none'] == $currentMemberData['card_lev'] || empty($currentMemberData['card_lev'])) && 'baodao' == $companyCode) {

                if (empty($currentMemberData['cardno'])) {
                    $createCardno = $this->createCardNo($jjUniId, $companyCode);
                    if (0 == $createCardno['status']) {
                        throw new \think\Exception($createCardno['msg']);
                    }
                    $updateData['cardno'] = $createCardno['data']['cardno'];
                }
                $updateData['card_lev'] = Constants::$cardLev['gold'];
                $res = $memberIndexModel->updateMemberIndex(['member_code' => $memberCode], $updateData);
                if (false === $res['status']) {
                    throw new \think\Exception($memberVipModel->getError());
                }
            }
            //平台
            if ('baodao' != $companyCode && 1 == $currentMemberData['mobile_status']) {
                if (empty($currentMemberData['cardno'])) {
                    $createCardno = $this->createCardNo($jjUniId, $companyCode);
                    if (0 == $createCardno['status']) {
                        throw new \think\Exception($createCardno['msg']);
                    }
                    $updateData['cardno'] = $createCardno['data']['cardno'];
                }
                $updateData['card_lev'] = Constants::$cardLev['gold'];
                $res = $memberIndexModel->updateMemberIndex(['member_code' => $memberCode], $updateData);
                if (false === $res['status']) {
                    throw new \think\Exception($memberVipModel->getError());
                }
            }
            // 如果该粉丝是会员，则同时更新会员信息，同时将vipId写入粉丝表中
            $vipInfo = $memberVipModel->where(['member_code' => $memberCode])->find();
            if ($vipInfo) {
                unset($updeData['mobile_status']);
                if (false === $memberVipModel->updateMemberVipByVipId($vipInfo['vip_id'], $updeData)) {
                    throw new \think\Exception($memberVipModel->getError());
                }
            } elseif ('baodao' != $companyCode && $currentMemberData['mobile_status'] == Constants::$mobileStatus['certified']) { // 如果不是会员，且手机号已认证
                // 根据手机号查询会员信息
                $memberVipData = $memberVipModel->getMemberVipData(['mobile' => $currentMemberData['mobile']], 'vip_id,cardno,card_lev');
                $memberIndexData = current($memberIndexData);
                // 如果存在会员信息，则合并
                if ($memberVipData) {
                    // 将粉丝的最新信息中非空的值更新到会员中
                    $memberVipData = $memberVipData->getData();
                    $vipId = $memberVipData['vip_id'];
                    unset($memberIndexData['jj_uni_id']);
                    if (false === $memberVipModel->updateVipData(['vip_id' => $vipId], $memberIndexData)) {
                        throw new \think\Exception($memberVipModel->getError());
                    }
                    // 将会员的信息更新到当前粉丝中
                    if (false === $memberIndexModel->updateMemberIndex(['member_code' => $memberCode], $memberVipData)) {
                        throw new \think\Exception($memberIndexModel->getError());
                    }
                } else {
                    // 如果不存在，则新增
                    $memberIndexInfoModel = new MemberIndexInfoModel($companyId);
                    $memberIndexInfoData = $memberIndexInfoModel->getMemberInfoData(['member_code' => $memberCode], 'first_p,first_store,first_qrscene');
                    $memberIndexInfoData || $memberIndexInfoData = []; // 如果没有数据，则赋值空数组
                    $mergeMemberData = array_merge($memberIndexData, current($memberIndexInfoData), $memberData); // 合并粉丝的数据，并使用最新的粉丝数据覆盖数据库中的数据
                    // 生成卡号和会员等级
                    if (!empty($mergeMemberData['cardno'])) {
                        $cardno = $mergeMemberData['cardno'];
                        $cardLev = $mergeMemberData['card_lev'];
                    } else {
                        $createCardno = $this->createCardNo($jjUniId, $companyCode);
                        if (0 == $createCardno['status']) {
                            throw new \think\Exception('card no create fail');
                        }
                        $cardno = $createCardno['data']['cardno'];
                        $cardLev = Constants::$cardLev['gold'];
                    }
                    $mergeMemberData['cardno'] = $cardno;
                    $mergeMemberData['card_lev'] = $cardLev;
                    $mergeMemberData['member_code'] = $memberCode;
                    // 添加会员数据
                    $mergeMemberData['add_ts'] = $mergeMemberData['last_ts'] = time();
                    unset($mergeMemberData['mobileStatus']);
                    unset($mergeMemberData['mobile_status']);
                    unset($mergeMemberData['jj_uni_id']);
                    unset($mergeMemberData['header_img']);
                    unset($mergeMemberData['account_code']);
                    unset($mergeMemberData['favour_store']);
                    unset($mergeMemberData['favour_p']);
                    unset($mergeMemberData['service_p']);
                    unset($mergeMemberData['service_store']);
                    unset($mergeMemberData['service_qrscene']);
                    unset($mergeMemberData['come_from']);
                    unset($mergeMemberData['mp_id']);
                    unset($mergeMemberData['vip_id']);
                    $vipId = $memberVipModel->insertGetId($mergeMemberData);
                    if (false === $vipId) {
                        throw new \think\Exception($memberVipModel->getError());
                    }
                    // 将vipId、卡号、等级更新到粉丝表中
                    if (false === $memberIndexModel->updateMemberIndex(['member_code' => $memberCode], ['vip_id' => $vipId, 'cardno' => $mergeMemberData['cardno'], 'card_lev' => $mergeMemberData['card_lev']])) {
                        throw new \think\Exception($memberVipModel->getError());
                    }
                }

                // 将memberCode和vipId加入更新队列
                //  $queueService = new QueueService();
                //  $queueService->push('update_vipid', ['companyId' => $companyId, 'memberCode' => $memberCode, 'vipId' => $vipId]);
            }
            if ('baodao' == $companyCode) {
                $arvatoMemberService = new ArvatoMemberService();
                $res = $arvatoMemberService->updateMemberInfo($jjUniId, $companyCode);
                // $pushToRedis = $this->pushMemberInfoToRedis($memberCode, $companyId);停用
            }
            $returnData = $viewMemberModel->getViewMemberIndexByCondition(['member_code' => $memberCode]);
            $memberIndexModel->commit();
        } catch (\Exception $exc) {
            $memberIndexModel->rollback();
            return ['status' => false, 'desc' => $exc->getMessage(), 'data' => $data];
        }
        return ['status' => true, 'desc' => 'success', 'data' => $returnData];
    }

    /**
     * 通过关键字获取会员列表
     * @param type $keyword
     * @param type $companyId
     * @return type
     */
    public function getMemberListByKeyword($keyword, $companyId, $page, $pageSize, $field = '*, from_unixtime(add_ts) as addTime, from_unixtime(last_ts) as lastTime') {
        $viewMemberModel = new ViewMemberIndexModel($companyId);
        $memberViewList = $viewMemberModel->getMemberListByKeyword($keyword, $page, $pageSize, $field); //先获取会员列表
        $returnList = $this->getMemberSignInfo($memberViewList, $companyId); //在获取最后一条签到信息
        return $returnList;
    }

    /**
     * 获取签到信息
     * @param type $memberViewList
     * @return boolean
     */
    public function getMemberSignInfo($memberViewList, $companyId) {
        if (empty($memberViewList || !array($memberViewList))) {
            return false;
        }
        foreach ($memberViewList['list'] as $key => $value) {
            $memberViewList['list'][$key]['serviceInfo'] = [];
            $map['member_code'] = ['in', explode(',', $value['memberCode'])];
            $memberSignModel = new MemberSignModel($companyId);
            $serviceData = $memberSignModel->findOneServiceDataDesc($map);
            $memberViewList['list'][$key]['serviceInfo'] = $serviceData ? $this->convertUnderline($serviceData) : (object) [];
        }

        $memberViewList['list'] = array_values($memberViewList['list']);
        return $memberViewList;
    }

    /**
     * 查询数据库是否能发送
     * @param type $params
     * @param type $companyId
     * @return type array
     */
    public function memberSendNoticeValidate($params, $companyId) {
        $mpsModel = new Mps();
        $mpInfo = $mpsModel->getMpsInfoByCondition(['o_id' => $companyId]);
        $viewMemberModel = new ViewMemberIndexModel($companyId);
        $list = $viewMemberModel->getMemberListByMobile(['jj_member_index_' . $companyId . '.mobile' => $params['mobile']]);
        $memberAddressModel = new VipsAddress($companyId);
        if (false === empty($list)) {
            //根据初绑门店ID查询门店名称
            $storeModel = new Store();
            $memberSign = new MemberSignModel($companyId);
            foreach ($list as $k => $v) {
                // $list[$k]['service_info'] = $memberSign->getMemberSignListByMemberCode($v['member_code']);
                if ($v['first_store']) {
                    $list[$k]['store_show_name'] = $storeModel->getStoreInfoStrByCondition(['store_id' => $v['first_store']], 'store_show_name');
                } else {
                    $list[$k]['store_show_name'] = '';
                }
                $list[$k] = $this->convertUnderline($list[$k]);
            }
            $mobileStatusFind = $viewMemberModel->getViewMemberIndexByCondition(['mobile' => $params['mobile'], 'mobile_status' => 1]);
            // $mobileStatusFind = $viewMemberModel->where(['mobile' => $params['mobile'], 'mobile_status' => 1])->find();
            if (!empty($mobileStatusFind)) {
                //已绑定，不发送验证码并返回会员信息
                $result['list'] = array_values($list);
                $result['type'] = 3;
                return ['desc' => '此手机号已认证', 'data' => $result];
            }
            $checkResult = $this->checkMemberBindStatus($params['mobile'], $companyId);
            //不发短信，返回list数据
            $data['type'] = $checkResult['type'];
            $data['list'] = array_values($list);
            if ($checkResult['type'] == 1) {
                $data['type'] = 1;
                return ['desc' => '此认证手机号有多个:短信发送失败', 'data' => $data];
            }
            if ($checkResult['type'] == 2) {
                $data['type'] = 2;
                return ['desc' => '此手机号已绑定过微信，不可再次绑定:短信发送失败', 'data' => $data];
            }
        }
        //可以发送验证码
        return ['desc' => 'success'];
    }

    /**
     * 判断手机号状态并返回相关数据；
     * 判断条件：判断认证手机号是否唯一数据，且是否绑定过微信 
     * @param   string      $mobileno   手机号
     * @status   on          启用状态
     * @Return : array(
     *                  'type' =>1, //场景类型 1:多条记录，直接展示记录; 2：单条记录，已有绑定信息，直接展示 3:单条信息且无绑定信息，发送验证码，提交正确的验证码后绑定 4：没有找到任何记录，走老流程
     *                  'data' =>array() , //1：会员信息  2 会员信息 3 会员信息 4 空
     *                  )
     * @Author : 
     * @Time  : 2017-6-21
     */
    protected function checkMemberBindStatus($mobile, $companyId) {
        $viewMemberIndexModel = new ViewMemberIndexModel($companyId);
        //查询是否有多个手机号    
        $memberIndexModel = new MemberIndexModel($companyId);
        $where = ['mobile' => $mobile];
        $mobileCount = $memberIndexModel->where($where)->count();
        $res = []; //定义返回结果数组
        //如果$memberList为空
        if (empty($mobileCount)) {
            $res['type'] = 4;
            return $res;
        }
        $memberInfoModel = new MemberIndexInfoModel($companyId); //声明会员信息类  
        $storeModel = new Store();
        //判断是否多条
        if ($mobileCount > 1) {
            $res['type'] = 1;
            //查出多条记录                    
            $memberData = $viewMemberIndexModel->getViewMemberListByCondition($where);
            foreach ($memberData as $key => $value) {
                //查询绑定信息和门店信息                
                $storeName = $storeModel->getStoreInfoStrByCondition(['store_id' => $value['first_store']], 'store_name');
                $memberData[$key]['storeName'] = $storeName;
                $memberData[$key]['openid'] = $value['account_code'];
            }
            $res['data'] = $this->convertUnderline($memberData);
        } else {
            //根据Vipid 检查info表是否有openid 
            $memberData = $viewMemberIndexModel->getViewMemberIndexByCondition(['mobile' => $mobile]); //获取微信绑定信息
            $storeName = $storeModel->getStoreInfoStrByCondition(['store_id' => $value['first_store']], 'store_name');
            $memberData['storeName'] = $storeName;
            if ($memberData['account_code']) {
                $res['type'] = 2;
                //根据VIPID查找会员信息                
                $memberData['openid'] = $memberData['account_code'];
            } else {
                $res['type'] = 3;
                //查询会员信息                
            }

            $res['data'] = $this->convertUnderline($memberData);
        }
        return $res;
    }

    /**
     * 通过memberCode获取需要存入缓存的值
     * @param type $memberCode
     */
    public function pushMemberInfoToRedis($memberCode, $companyId = 1, $functionName = 'newMember', $params = []) {
        $viewMemberIndex = new ViewMemberIndexModel($companyId);
        $memberInfo = current($viewMemberIndex->getIndexAndvipData(['member_code' => $memberCode]));
        isset($memberInfo['mobile']) && $data['mobile'] = $memberInfo['mobile'];
        isset($memberInfo['name']) && $data['name'] = $memberInfo['name'];
        isset($memberInfo['gender']) && $data['gender'] = $memberInfo['gender'];
        isset($memberInfo['birthday']) && $data['birthday'] = $memberInfo['birthday'];
        isset($memberInfo['cardno']) && $data['card_no'] = $memberInfo['cardno'];
        isset($params['wx_avatar_url']) && $data['wx_avatar_url'] = $params['wx_avatar_url']; //可能需要附加参数确认
        isset($params['account_code']) && $data['wx_openid'] = $params['account_code'];
        isset($params['wx_nick_name']) && $data['wx_nick_name'] = $params['wx_nick_name']; //可能需要附加参数确认
        isset($params['wx_sex']) && $data['wx_sex'] = $params['wx_sex']; //可能需要附加参数确认
        isset($params['wx_language']) && $data['wx_language'] = $params['wx_language']; //可能需要附加参数确认
        isset($params['wx_city']) && $data['wx_city'] = $params['wx_city']; //可能需要附加参数确认
        isset($params['wx_province']) && $data['wx_province'] = $params['wx_province']; //可能需要附加参数确认
        isset($params['wx_country']) && $data['wx_country'] = $params['wx_country']; //可能需要附加参数确认
        isset($params['wx_subscribe_time']) && $data['wx_subscribe_time'] = $params['wx_subscribe_time']; //可能需要附加参数确认
        isset($params['wx_unionid']) && $data['wx_unionid'] = $params['wx_unionid']; //可能需要附加参数确认
        isset($memberInfo['first_store']) && $data['shop_code'] = $memberInfo['first_store'];
        isset($memberInfo['first_p']) && $data['emp_code'] = $memberInfo['first_p'];
        isset($memberInfo['come_form']) && $data['channel_code'] = $memberInfo['come_form'];
        isset($params['campaign_code']) && $data['campaign_code'] = $params['campaign_code']; //可能需要附加参数确认
        $data['reg_type'] = $this->getRegType($memberInfo);
        $arvatoMember = new CommonPush();
        $push = $arvatoMember->pushToRedis($data, $functionName);
        return $push;
    }

    /**
     * 获取注册类型
     * @param type $memberInfo
     * @return int
     */
    public function getRegType($memberInfo) {
        if (!empty($memberInfo['mobile']) && !empty($memberInfo['name']) && !empty($memberInfo['mobile']) && !empty($memberInfo['mobile']) && 1 == $memberInfo['mobile_status']) {
            return Constants::$memberStatus['registered'];
        } else if (!empty($memberInfo['mobile']) || !empty($memberInfo['name']) || !empty($memberInfo['mobile']) || !empty($memberInfo['mobile'])) {
            return Constants::$memberStatus['potential'];
        } else {
            return Constants::$memberStatus['follower'];
        }
    }

    /**
     * 获取memberInfo
     * @param type $condition
     * @param type $companyId
     * @return type array
     */
    public function getViewMemberInfoByCondition($condition, $companyId) {
        $viewMemberModel = new ViewMemberIndexModel($companyId);
        $memberInfo = $viewMemberModel->getViewInfoByCondition($condition);
        return $this->convertUnderline(current(array_values($memberInfo)));
    }

    /**
     * 获取用户详情
     * @param type $parmas
     * @param type $companyId
     * @return boolean
     */
    public function getMemberInfo($parmas, $companyId) {
        $viewMemberIndexModel = new ViewMemberIndexModel($companyId);
        $memberData = [];
        $memberCode = $parmas['memberCode'];
        $viewMemberInfo = $viewMemberIndexModel->getViewInfoByCondition(['member_code' => $memberCode]);
        if (empty($viewMemberInfo)) {
            return false;
        }
        $viewMemberInfo = current($viewMemberInfo);
        $memberData = $viewMemberInfo;
        $grantId = $viewMemberInfo['grant_id'];
        $memberData['isFaceGrant'] = 0;
        if (false === empty($grantId)) {
            $memberData['isFaceGrant'] = 1;
        }
        $memberData['openid'] = $memberData['account_code'];
        $vipAddressModel = new VipsAddress($companyId);
        $memberData['defaultShippingAddress'] = [];
        $memberAddress = $vipAddressModel->getAddressInfoByConditon(['member_code' => ['in', explode(',', $memberData['member_code'])], 'is_def' => 1], 'receive_name,province_name,city_name,area_name,zipcode,address,mobile');
        // 获取粉丝默认收货地址
        $memberData['defaultShippingAddress'] = [];
        if (!empty($memberAddress)) {
            $memberData['defaultShippingAddress'] = $memberAddress->getData();
        }
        // 获取初绑门店名称
        if (!empty($memberData['first_store'])) {
            $storesModel = new Store();
            $storeData = $storesModel->getStoreByCondition(['store_id' => $memberData['first_store']], 'store_show_name');
            if (!empty($storeData)) {
                $memberData = array_merge($memberData, ['store_show_name' => $storeData['store_show_name']]);
            }
        }
        // 获取初绑验光师名称
        if (!empty($memberData['first_p'])) {
            $staffModel = new Staffs();
            $staffData = $staffModel->getStaffInfoByCondtion(['staff_id' => $memberData['first_p']], 'staff_name');
            if (!empty($staffData)) {
                $memberData = array_merge($memberData, ['staff_name' => $staffData['staff_name']]);
            }
        }
        $memberData['memberCode'] = $memberCode;
        return Helper::convertUnderlineArray($memberData);
    }

    /**
     * 获取家庭成员信息
     * @param type $params
     * @param type $companyId
     * @return boolean
     */
    public function getFamilyInfo($params, $companyId) {
        $viewMemberModel = new ViewMemberIndexModel($companyId);
        $memberIndexModel = new MemberIndexModel($companyId);
        $memberInfo = $viewMemberModel->getIndexAndvipData(['member_code' => $params['memberCode']]);
        //检查会员是否存在  $memberInfo是拼接后的数据
        if (!$memberInfo) {
            return false;
        }
        $memberFamilysModel = new MemberFamilys($companyId);
        $list = collection($memberFamilysModel->getListByCondition(['my_member_code' => ['in', explode(',', current($memberInfo)['member_code'])]], 'family_id,family_member_code,tie_id,call,add_ts'))->toArray();
        //$list = $MemberFamilysModel->where($where)->order('add_ts desc')->field('family_id,family_vip_id,tie_id,call,add_ts')->select();
        //echo $MemberFamilysModel->getLastSql();die;
        if ($list) {
            foreach ($list as $key => $value) {
                $familyInfo = $viewMemberModel->getViewMemberIndexByCondition(['member_code' => $value['family_member_code']]);
                if (!empty($familyInfo)) {
                    $list[$key]['family_info'] = $familyInfo;
                    continue;
                }
                $list[$key]['family_info'] = '{}';
            }
            return Helper::convertUnderlineArray($list);
        }
        return false;
    }

    /**
     * 家庭成员关系绑定
     * @param type $parmas
     * @param type $companyId
     * @return type
     */
    public function familyRelationBind($parmas, $companyId) {
        $memberIndexModel = new MemberIndexModel($companyId);
        //检查会员是否存在
        $memberIndexModel->startTrans();
        try {
            foreach ($parmas['memberRelation'] as $key => $value) {
                $memberInfo = $memberIndexModel->getMemberInfoByCondition(['member_code' => $value['myMemberCode']]);
                if (!$memberInfo) {
                    throw new \think\Exception('父级memberCode不存在，不可绑定');
                }
                $memberInfo = $memberIndexModel->getMemberInfoByCondition(['member_code' => $value['familyMemberCode']]);
                if (!$memberInfo) {
                    throw new \think\Exception('子级memberCode不存在，不可绑定');
                }
                if ($value['memberCode'] == $value['familyMemberCode']) {
                    throw new \think\Exception('不可自身绑定家庭成员关系');
                }
                //检查这个绑定关系配置是否存在
                $familyTiesModel = new FamilysTies($companyId);
                $familyTieInfo = $familyTiesModel->getOneByCondition(['tie_id' => $value['tieId']]);
                if (!$familyTieInfo) {
                    throw new \think\Exception('不存在的绑定关系');
                }
                $memberFamilyModel = new MemberFamilys($companyId);
                $data = [
                    'my_member_code' => $value['myMemberCode'],
                    'family_member_code' => $value['familyMemberCode'],
                    'tie_id' => $value['tieId'],
                    'call' => $familyTieInfo['call'],
                    'add_ts' => time()
                ];
                $result = $memberFamilyModel->addMemberFamily($data);
                if (empty($result)) {
                    throw new \think\Exception($memberFamilyModel->getError());
                }
                $viewMemberModel = new ViewMemberIndexModel($companyId);
                $arvatoData['card_no1'] = $viewMemberModel->getViewMemberIndexByCondition(['member_code' => $value['myMemberCode']])['cardno'];
                $arvatoData['card_no2'] = $viewMemberModel->getViewMemberIndexByCondition(['member_code' => $value['familyMemberCode']])['cardno'];
                $arvatoData['relation_code'] = $familyTiesModel->where(['tie_id' => $value['tieId']])->value('call');
                $staffModel = new Staffs();
                $arvatoData['emp_code'] = $staffModel->where(['staff_id' => $parmas['staffId']])->value('staff_job_id');
                $functionName = 'addFamily';
                $arvatoMember = new CommonPush();
                $push = $arvatoMember->pushToRedis($arvatoData, $functionName);
            }
            $memberIndexModel->commit();
        } catch (\Exception $exc) {
            $memberIndexModel->rollback();
            return ['msg' => $exc->getMessage(), 'data' => $data];
        }
        return ['msg' => 'success'];
    }

    /**
     * 开始或者结束服务
     * @param type $params
     * @param type $companyId
     * @return type
     */
    public function serviceAction($params, $companyId) {
        if (empty($params['msId']) && empty($params['yId'])) {
            return ['msg' => 'msId与，yId不能同时为空'];
        }
        if (!empty($params['msId']) && !empty($params['yId'])) {
            return ['msg' => 'msId与yId不能同时存在'];
        }
        //检查粉丝是否存在
        $viewMemberModel = new ViewMemberIndexModel($companyId);
        $data = $viewMemberModel->getViewInfoByCondition(['member_code' => $params['memberCode']]);
        $checkData = current($data);
        if (empty($checkData)) {
            return ['msg' => '会员信息不存在'];
        }
        //修改服务状态
        $result = $this->startAndEnd($params, $companyId);
        if ($result) {
            $memberSignModel = new MemberSignModel($companyId);
            $where = ['ms_id' => $params['msId']];
            $whereOr = ['y_id' => $params['yId']];
            $data = $memberSignModel->getMemberSignByYidOrMsId($where, $whereOr, 'ms_id, status');
            $returnData = $this->convertUnderline($data->getData());
            return ['msg' => 'success', 'data' => $returnData];
        }

        return ['msg' => '服务修改失败'];
    }

    public function startAndEnd($args, $companyId) {
        if (!empty($args['msId'])) {
            //根据服务ID
            if (!in_array($args['status'], [2, 3])) {
                return ['msg' => 'status参数不正确'];
            }
            //获得服务信息
            $memberSignModel = new MemberSignModel($companyId);
            $serviceInfo = $memberSignModel->getMemberSignByCondition(['ms_id' => $args['msId']], '*');
            if (!$serviceInfo) {
                return ['msg' => '此服务不存在'];
            }
            if ($args['status'] == 2 && $serviceInfo['status'] != 1) {
                return ['msg' => '此服务当前状态并非等待中，不可开始服务'];
            } elseif ($args['status'] == $serviceInfo['status']) {
                return ['msg' => '此服务状态未改变'];
            }
            if ($args['status'] == 2) {
                $update['status'] = 2;
            } elseif ($args['status'] == 3) {
                $update['status'] = 3;
                $update['end_time'] = time();
            }
            //修改状态
            $res = $memberSignModel->saveMemberSign($update, ['ms_id' => $args['msId']]);
            return ['msg' => 'success'];
        } else { //预约ID，只能是开始服务
            //结束所有服务
            $memberSignModel = new MemberSignModel($companyId);
            $memberSignModel->closeOtherService($args['memberCode']);
            //同时完成预约单
            $memberReserveModel = new MemberReserve();
            $update = $memberReserveModel->save(['reserve_status_id' => Constants::$reserveStatusId['finished']], ['mr_id' => $args['yId']]);
            $data['res_id'] = $args['yId'];
            $data['status'] = Constants::$reserveStatusId['finished'];
            $arvatoRedis = new CommonPush();
            $res = $arvatoRedis->pushToRedis($data, 'updateReserve');
            //添加一条
            $value = [
                'member_code' => $args['memberCode'],
                'type' => 2,
                'status' => 2, //预约只能开始，如果要结束，请通过service_id来做
                'come_from' => $args['comeFrom'],
                'service_store' => $args['serviceStore'],
                'service_p' => $args['serviceP'],
                'y_id' => $args['yId'],
                'start_time' => time(),
                'add_ts' => time(),
                    //  'vip_id'        => $args['vipId']
            ];

            $resId = $memberSignModel->addMemberSign($value);
            $memberModel = new ViewMemberIndexModel($companyId);
            $memberInfo = current($memberModel->getIndexAndvipData(['member_code' => $args['memberCode']]));
            $commonPush = new \app\common\arvato\CommonPush();
            $value = array_diff($value, ['', false]); //去掉空值
            $storeModel = new Store();
            $shopCode = $storeModel->where(['store_id' => $args['serviceStore']])->value('trusteeship_id');
            $data = ['mobile' => $memberInfo['mobile'], 'queue_id' => $resId, 'openid' => $memberInfo['account_code'], 'card_no' => $memberInfo['cardno'], 'shop_code' => $shopCode, 'sign_time' => (string) date('Y-m-d H:i:s'), 'sign_type' => '1'];
            if ($args['yId']) {//如果是预约
                $data['res_id'] = (string) $args['yId'];
                $data['sign_type'] = '2';
            }
            $commonPush->pushToRedis($data, 'memberSignIn');
            return $resId;
        }
    }

    public function mobileCanBind($companyId, $mobile) {
        //查询视图中手机号对应的card_no是否为空
        $viewMemberIndexModel = new ViewMemberIndexModel($companyId);

        $viewMemberIndex = $viewMemberIndexModel->getViewMemberIndexByCondition(['mobile' => $mobile, "mobile_status" => 1]);
        if (empty($viewMemberIndex['account_code'])) {
            return true;
        }
        return false;
    }

    /**
     * 删除一条家庭关系
     * @param type $familyId
     * @param type $companyId
     * @return type bool
     */
    public function removeFamily($params, $companyId) {
        $familyModel = new MemberFamilys($companyId);
        $familyInfo = $familyModel->getFamilyInfoById($params['familyId']);
        if (empty($familyInfo)) {
            return false;
        }
        $familyData = $familyInfo->getData();
        $memberIndexModel = new MemberIndexModel($companyId);
        $data['card_no1'] = $memberIndexModel->getMemberInfoByCondition(['member_code' => $familyData['my_member_code']], 'cardno')['cardno'];
        $data['card_no2'] = $memberIndexModel->getMemberInfoByCondition(['member_code' => $familyData['family_member_code']], 'cardno')['cardno'];
        $staffModel = new Staffs();
        $data['emp_code'] = $staffModel->getStaffInfoByCondtion($condition, 'staff_job_id')['staff_job_id'];
        $commonPush = new \app\common\arvato\CommonPush();
        $res = $commonPush->pushToRedis($data, 'removeFamily');
        $remove = $familyModel->removeFamilyRelation($params['familyId']);
        return $remove;
    }

    /**
     * 获取标签值
     * @param type $tagIdString
     * @return boolean
     */
    public function getTagValueArrayByTagIdString($tagIdString, $companyId) {
        if (empty($tagIdString)) {
            return false;
        }
        $arr = explode(',', $tagIdString);
        $returnData = [];
        $tagModel = new Tags($companyId);
        foreach ($arr as $key => $value) {
            $returnData[] = $tagModel->where(['tag_id' => $value])->value('name');
        }
        return $returnData;
    }

}
